package com.zhentao.config;

import com.alibaba.nacos.api.utils.StringUtils;
import com.zhentao.utils.JwtService;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class AuthorizeFilter implements Ordered, GlobalFilter {
    @Resource
    private RedisCacheUtil redisCacheUtil;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2.判断是否是登录
        if(request.getURI().getPath().contains("/login") || request.getURI().getPath().contains("UploadQuestion") || request.getURI().getPath().contains("/user/logout") || request.getURI().getPath().contains("/user/userdata") || request.getURI().getPath().contains("getMenusUrl") || request.getURI().getPath().contains("ImageSubmission")|| request.getURI().getPath().contains("upload") || request.getURI().getPath().contains("/examination/logout")){
            //放行
            System.out.println(request.getURI().getPath()+"过滤器-放行");
            return chain.filter(exchange);
        }
        //3.获取token
        String token = request.getHeaders().getFirst("Authorization");
        System.out.println("token"+token);
        //4.判断token是否存在
        if(StringUtils.isBlank(token)){
            System.out.println("没有token");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        Map<String, Object> map = JwtService.getClaimsMap(token);
        if (map != null) {
//            状态续期
            System.out.println("状态续期");
            redisTemplate.opsForValue().set("user_session:"+map.toString().split("nickname=")[1].split(",")[0],"0",30*60, TimeUnit.SECONDS );
        }
        //5.判断token是否有效
        try {
            Claims claimsBody = JwtService.getClaimsBody(token);
            //是否是过期
            int result = JwtService.verifyToken(claimsBody);
            if(result == 0 || result == 2){
                //如果过期删除token
                redisCacheUtil.redisTemplate.delete(token);
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
        }catch (Exception e){
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //6.放行
        return chain.filter(exchange);
    }

    /**
     * 设置优先级，数字越小优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}